package com.hue.client.service;

import com.hue.spring.annotation.Component;
import com.hue.spring.init.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/*
    实现BeanPostProcessor来自定义每个bean在初始化前后需要执行的方法
 */
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessorBeforeInitialization(Object bean, String beanName) {
//        System.out.println(beanName + "调用了初始化之前的方法");
        return bean;
    }

    @Override
    public Object postProcessorAfterInitialization(Object bean, String beanName) {
//        System.out.println(beanName + "调用了初始化之后的方法");
        //为userServiceImpl生成代理对象
        if (beanName.equals("userServiceImpl")) {
            Object proxyUserServiceImpl = Proxy.newProxyInstance(BeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                    System.out.println("执行了userServiceImpl的代理逻辑");
                    //执行正常的业务逻辑
                    Object invoke = method.invoke(bean, objects);
                    return invoke;
                }
            });
            return proxyUserServiceImpl;
        }
        return bean;
    }
}
